{% extends "base.html" %}

{% set current_menu = 'work_hour' %}
{% set current_page = 'stats' %}

{% block title %}工时统计{% endblock %}

{% block content %}
<div class="container mx-auto">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('project.list_projects') }}" class="text-gray-500 hover:text-gray-700">项目管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">工时统计</li>
        </ol>
    </nav>
    
    <!-- 总体统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4">
            <h3 class="text-lg font-semibold text-gray-700">总工时</h3>
            <p class="text-3xl font-bold text-blue-600">{{ "%.1f"|format(stats.total_work_hours) }}</p>
            <p class="text-sm text-gray-500">小时</p>
        </div>

        <div class="bg-white rounded-lg shadow p-4">
            <h3 class="text-lg font-semibold text-gray-700">项目总数</h3>
            <p class="text-3xl font-bold text-purple-600">{{ stats.total_projects }}</p>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <h3 class="text-lg font-semibold text-gray-700">任务总数</h3>
            <p class="text-3xl font-bold text-yellow-600">{{ stats.total_tasks }}</p>
        </div>
    </div>
    
    <!-- 项目选择 -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
        <div class="flex flex-wrap items-center gap-4">
            <div>
                <label class="block text-gray-700 text-sm font-bold mb-2" for="project_select">
                    选择项目
                </label>
                <select class="shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="project_select" onchange="window.location.href='/work_hour/stats?project_id=' + this.value">
                    <option value="">-- 所有项目 --</option>
                    {% for project in projects %}
                    <option value="{{ project.id }}" {% if selected_project and selected_project.id == project.id %}selected{% endif %}>{{ project.name }}</option>
                    {% endfor %}
                </select>
            </div>
            {% if selected_project %}
            <div class="ml-auto">
                <a href="{{ url_for('project.view_project', project_id=selected_project.id) }}" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                    返回项目详情
                </a>
            </div>
            {% endif %}
        </div>
    </div>
    
    {% if selected_project %}
    <!-- 项目详情 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <div class="flex justify-between items-start mb-4">
            <div>
                <h2 class="text-xl font-semibold">{{ selected_project.name }}</h2>
                <p class="text-gray-600">{{ selected_project.description }}</p>
            </div>
            <div class="text-right">
                <span class="px-3 py-1 rounded-full text-sm font-semibold
                    {% if selected_project.status == '未开始' %}bg-gray-200 text-gray-800
                    {% elif selected_project.status == '进行中' %}bg-yellow-200 text-yellow-800
                    {% elif selected_project.status == '已完成' %}bg-green-200 text-green-800
                    {% elif selected_project.status == '已延期' %}bg-red-200 text-red-800
                    {% endif %}">
                    {{ selected_project.status }}
                </span>
            </div>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            <div>
                <p class="text-gray-600">项目经理</p>
                <p class="font-semibold">{{ selected_project.manager.name if selected_project.manager else '未分配' }}</p>
            </div>
            <div>
                <p class="text-gray-600">项目预算</p>
                <p class="font-semibold">{{ "%.2f"|format(selected_project.budget) }} 万元</p>
            </div>
            <div>
                <p class="text-gray-600">项目周期</p>
                <p class="font-semibold">
                    {{ selected_project.start_date|format_date }} - {{ selected_project.end_date|format_date }}
                </p>
            </div>
        </div>
    </div>
    
    <!-- 任务工时统计 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h3 class="text-lg font-semibold mb-4">任务工时统计</h3>
        {% if tasks %}
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务名称</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">负责人</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工时</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">进度</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for task in tasks %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ task.name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">{{ task.assignee.name if task.assignee else '未分配' }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ "%.1f"|format(task.work_hour) if task.work_hour else 0 }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                {% if task.status == '未开始' %}bg-gray-100 text-gray-800
                                {% elif task.status == '进行中' %}bg-yellow-100 text-yellow-800
                                {% elif task.status == '已完成' %}bg-green-100 text-green-800
                                {% elif task.status == '已延期' %}bg-red-100 text-red-800
                                {% endif %}">
                                {{ task.status }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full" style="width: {{ task.progress }}%"></div>
                            </div>
                            <div class="text-xs text-gray-600">{{ task.progress }}%</div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <p class="text-gray-500">暂无任务</p>
        {% endif %}
    </div>
    
    <!-- 工时记录列表 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">工时记录</h3>
            <button onclick="document.getElementById('workHourModal').classList.remove('hidden')" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                添加工时记录
            </button>
        </div>
        
        {% if work_hour_records %}
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务名称</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">记录人</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工时</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工作日期</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for work_hour, task, user in work_hour_records %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ task.name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">{{ user.name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ "%.1f"|format(work_hour.work_hours) }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ work_hour.work_date|format_date }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {% if work_hour.start_time and work_hour.end_time %}
                                {{ work_hour.start_time.strftime('%H:%M') }} - {{ work_hour.end_time.strftime('%H:%M') }}
                            {% elif work_hour.start_time %}
                                {{ work_hour.start_time.strftime('%H:%M') }} 起
                            {% elif work_hour.end_time %}
                                至 {{ work_hour.end_time.strftime('%H:%M') }}
                            {% else %}
                                未记录
                            {% endif %}
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">{{ work_hour.description or '无描述' }}</div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <p class="text-gray-500">暂无工时记录</p>
        {% endif %}
    </div>
    
    <!-- 工时记录添加模态框 -->
    <div id="workHourModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-semibold mb-4">添加工时记录</h3>
                <form action="{{ url_for('work_hour.create') }}" method="post">
                    <div class="mb-4">
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="project_id">
                            项目 <span class="text-red-500">*</span>
                        </label>
                        <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="project_id" name="project_id" required>
                            {% for project in projects %}
                            <option value="{{ project.id }}">{{ project.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="task_id">
                            任务 <span class="text-red-500">*</span>
                        </label>
                        <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="task_id" name="task_id" required>
                            {% for task in user_tasks %}
                            <option value="{{ task.id }}">{{ task.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="hours">
                            工时（小时） <span class="text-red-500">*</span>
                        </label>
                        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="hours" name="hours" type="number" step="0.5" min="0" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="work_date">
                            工作日期 <span class="text-red-500">*</span>
                        </label>
                        <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="work_date" name="work_date" type="date" value="{{ today }}" required>
                    </div>
                    <div class="mb-4">
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="description">
                            描述
                        </label>
                        <textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="document.getElementById('workHourModal').classList.add('hidden')" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                            取消
                        </button>
                        <button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                            添加
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {% else %}
    <!-- 未选择项目时的图表和统计 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        <!-- 用户工时分布图 -->
        <div class="bg-white rounded-lg shadow p-6">
            <h3 class="text-lg font-semibold mb-4">用户工时分布</h3>
            {% if user_work_hours %}
            <div id="userWorkHourChart" style="width: 100%; height: 300px;"></div>
            {% else %}
            <p class="text-gray-500 text-center py-8">暂无工时数据</p>
            {% endif %}
        </div>
        

    </div>
    
    <!-- 用户工时统计表格 -->
    <div class="bg-white rounded-lg shadow p-6">
        <h3 class="text-lg font-semibold mb-4">用户工时统计</h3>
        {% if user_work_hours %}
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">部门</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工时</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">占比</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for user_data in user_work_hours %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ user_data.user.name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">{{ user_data.user.department or '未分配' }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ "%.1f"|format(user_data.hours) }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full" style="width: {{ (user_data.hours / stats.total_work_hours * 100) if stats.total_work_hours > 0 else 0 }}%"></div>
                            </div>
                            <div class="text-xs text-gray-600">{{ "%.1f"|format(user_data.hours / stats.total_work_hours * 100) if stats.total_work_hours > 0 else 0 }}%</div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <p class="text-gray-500">暂无工时数据</p>
        {% endif %}
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
{{ super() }}
<script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
<script>
    // 重置筛选条件
    function resetFilters() {
        document.getElementById('project_filter').value = '';
        document.getElementById('status_filter').value = '';
        document.getElementById('assignee_filter').value = '';
        document.getElementById('filterForm').submit();
    }
    
    // 打开工时记录模态框
    function openWorkHourModal() {
        document.getElementById('workHourModal').classList.remove('hidden');
        document.getElementById('taskInfo').classList.add('hidden');
        document.getElementById('firstTimeTip').classList.remove('hidden');
    }
    
    // 打开工时记录模态框（带任务信息）
    function openWorkHourModalWithTask(taskId, taskName, projectId, projectName) {
        document.getElementById('workHourModal').classList.remove('hidden');
        document.getElementById('taskId').value = taskId;
        document.getElementById('taskName').textContent = taskName;
        document.getElementById('projectName').textContent = projectName;
        document.getElementById('taskInfo').classList.remove('hidden');
        document.getElementById('firstTimeTip').classList.add('hidden');
        
        // 加载任务信息
        fetch(`/api/task/${taskId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('plannedHours').textContent = data.task.planned_hours || '未设置';
                    document.getElementById('actualHours').textContent = data.task.actual_hours || '0';
                }
            })
            .catch(error => {
                console.error('Error loading task info:', error);
            });
    }
    
    // 关闭工时记录模态框
    function closeWorkHourModal() {
        document.getElementById('workHourModal').classList.add('hidden');
        document.getElementById('workHourForm').reset();
    }
    
    // 检查时间偏差
    function checkTimeDeviation() {
        const plannedHours = parseFloat(document.getElementById('plannedHours').textContent) || 0;
        const actualHours = parseFloat(document.getElementById('actualHours').textContent) || 0;
        const newHours = parseFloat(document.getElementById('hours').value) || 0;
        
        const totalActualHours = actualHours + newHours;
        
        if (plannedHours > 0) {
            const deviation = ((totalActualHours - plannedHours) / plannedHours) * 100;
            
            if (Math.abs(deviation) > 20) {
                const message = deviation > 0 
                    ? `实际工时将超出计划工时${deviation.toFixed(1)}%，是否继续？` 
                    : `实际工时将低于计划工时${Math.abs(deviation).toFixed(1)}%，是否继续？`;
                
                if (!confirm(message)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    // 提交工时记录
    document.getElementById('workHourForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 验证开始时间和结束时间
        const startTime = document.getElementById('start_time').value;
        const endTime = document.getElementById('end_time').value;
        
        if (startTime && endTime) {
            const start = new Date(`2000-01-01T${startTime}`);
            const end = new Date(`2000-01-01T${endTime}`);
            
            if (end <= start) {
                showFlashMessage('结束时间必须晚于开始时间', 'error');
                return;
            }
        }
        
        if (!checkTimeDeviation()) {
            return;
        }
        
        const taskId = document.getElementById('taskId').value;
        const hours = document.getElementById('hours').value;
        const workDate = document.getElementById('workDate').value;
        const description = document.getElementById('description').value;
        
        fetch('/api/work_hours', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                task_id: taskId,
                hours: hours,
                work_date: workDate,
                start_time: startTime,
                end_time: endTime,
                description: description
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showFlashMessage('工时记录成功！', 'success');
                closeWorkHourModal();
                location.reload();
            } else {
                showFlashMessage('记录失败：' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error recording work hours:', error);
            showFlashMessage('记录失败，请稍后重试', 'error');
        });
    });
    
    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'not_started': '未开始',
            'in_progress': '进行中',
            'completed': '已完成',
            'closed': '已关闭'
        };
        return statusMap[status] || status;
    }
</script>

{% if not selected_project and user_work_hours %}
<script>
    {% if user_work_hours %}
    // 用户工时分布图
    const userWorkHourChart = echarts.init(document.getElementById('userWorkHourChart'));
    const userWorkHourOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        xAxis: {
            type: 'category',
            data: [
                {% for user_data in user_work_hours %}
                '{{ user_data.user.name }}'{% if not loop.last %},{% endif %}
                {% endfor %}
            ],
            axisLabel: {
                interval: 0,
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            name: '工时（小时）'
        },
        series: [{
            name: '工时',
            type: 'bar',
            data: [
                {% for user_data in user_work_hours %}
                {{ user_data.hours }}{% if not loop.last %},{% endif %}
                {% endfor %}
            ],
            itemStyle: {
                color: 'rgba(54, 162, 235, 0.8)'
            }
        }]
    };
    userWorkHourChart.setOption(userWorkHourOption);
    {% endif %}
    

    
    // 响应窗口大小变化
    window.addEventListener('resize', function() {
        {% if user_work_hours %}
        userWorkHourChart.resize();
        {% endif %}
    });
</script>
{% endif %}
{% endblock %}